<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>短信验证码登录</title>
  <!-- 引入Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- 引入Font Awesome -->
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  
  <!-- 配置Tailwind自定义主题 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36CFC9',
            neutral: '#F5F7FA',
            dark: '#1D2129',
            light: '#F2F3F5'
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  
  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .text-shadow {
        text-shadow: 0 2px 4px rgba(0,0,0,0.1);
      }
      .transition-custom {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      }
    }
  </style>
</head>
<body class="font-inter bg-gradient-to-br from-blue-50 to-indigo-100 min-h-screen flex items-center justify-center p-4">
  <!-- 登录卡片 -->
  <div class="w-full max-w-md bg-white rounded-2xl shadow-lg overflow-hidden transform transition-all duration-300 hover:shadow-xl">
    <!-- 卡片头部 -->
    <div class="bg-primary p-6 text-white text-center">
      <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-shadow">账号登录</h1>
      <p class="mt-2 opacity-90">使用手机号验证码登录</p>
    </div>
    
    <!-- 登录表单 -->
    <div class="p-6 md:p-8">
      <form id="loginForm" class="space-y-5">
        <!-- 手机号输入框 -->
        <div class="space-y-2">
          <label for="phoneNumber" class="block text-sm font-medium text-gray-700">手机号</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <i class="fa fa-phone text-gray-400"></i>
            </div>
            <input type="tel" id="phoneNumber" name="phoneNumber" 
                  class="w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom outline-none"
                  placeholder="请输入手机号" maxlength="11" required>
            <div id="phoneError" class="hidden mt-1 text-sm text-red-500"></div>
          </div>
        </div>
        
        <!-- 验证码输入框和发送按钮 -->
        <div class="space-y-2">
          <label for="code" class="block text-sm font-medium text-gray-700">验证码</label>
          <div class="flex space-x-3">
            <div class="relative flex-1">
              <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <i class="fa fa-shield text-gray-400"></i>
              </div>
              <input type="text" id="code" name="code" 
                    class="w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom outline-none"
                    placeholder="请输入6位验证码" maxlength="6" required>
              <div id="codeError" class="hidden mt-1 text-sm text-red-500"></div>
            </div>
            <button type="button" id="getCodeBtn" 
                  class="whitespace-nowrap px-4 py-3 bg-primary hover:bg-primary/90 text-white font-medium rounded-lg transition-custom focus:outline-none focus:ring-2 focus:ring-primary/50 focus:ring-offset-2">
              获取验证码
            </button>
          </div>
        </div>
        
        <!-- 登录按钮 -->
        <button type="submit" id="loginBtn" 
              class="w-full py-3 bg-primary hover:bg-primary/90 text-white font-medium rounded-lg transition-custom focus:outline-none focus:ring-2 focus:ring-primary/50 focus:ring-offset-2 flex items-center justify-center">
          <span>登录</span>
          <i class="fa fa-arrow-right ml-2"></i>
        </button>
      </form>
      
      <!-- 注册链接 -->
      <div class="mt-6 text-center">
        <p class="text-gray-600">
          还没有账号？
          <a href="#" id="registerLink" class="text-primary hover:text-primary/80 font-medium transition-custom">
            立即注册
          </a>
        </p>
      </div>
    </div>
  </div>
  
  <!-- 通知提示框 -->
  <div id="toast" class="fixed top-5 right-5 max-w-xs p-4 rounded-lg shadow-lg transform transition-all duration-300 translate-x-full opacity-0 flex items-center z-50">
    <div id="toastIcon" class="mr-3 text-xl"></div>
    <div id="toastMessage" class="flex-1"></div>
  </div>

  <script>
    // DOM元素
    const loginForm = document.getElementById('loginForm');
    const phoneNumber = document.getElementById('phoneNumber');
    const code = document.getElementById('code');
    const getCodeBtn = document.getElementById('getCodeBtn');
    const loginBtn = document.getElementById('loginBtn');
    const registerLink = document.getElementById('registerLink');
    const phoneError = document.getElementById('phoneError');
    const codeError = document.getElementById('codeError');
    const toast = document.getElementById('toast');
    const toastIcon = document.getElementById('toastIcon');
    const toastMessage = document.getElementById('toastMessage');
    
    // 后端API基础URL（根据实际情况修改）
    const API_BASE_URL = 'http://localhost:9876';
    
    // 显示通知提示
    function showToast(message, isSuccess = true) {
      toastMessage.textContent = message;
      toastIcon.className = isSuccess ? 'fa fa-check-circle text-green-500 mr-3 text-xl' : 'fa fa-exclamation-circle text-red-500 mr-3 text-xl';
      toast.classList.remove('translate-x-full', 'opacity-0');
      toast.classList.add(isSuccess ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800');
      
      setTimeout(() => {
        toast.classList.add('translate-x-full', 'opacity-0');
      }, 3000);
    }
    
    // 手机号验证
    function validatePhone(phone) {
      const regex = /^1[3-9]\d{9}$/;
      if (!regex.test(phone)) {
        phoneError.textContent = '请输入有效的手机号';
        phoneError.classList.remove('hidden');
        return false;
      }
      phoneError.classList.add('hidden');
      return true;
    }
    
    // 验证码验证
    function validateCode(code) {
      const regex = /^\d{6}$/;
      if (!regex.test(code)) {
        codeError.textContent = '请输入6位数字验证码';
        codeError.classList.remove('hidden');
        return false;
      }
      codeError.classList.add('hidden');
      return true;
    }
    
    // 发送验证码
    async function sendVerificationCode() {
      const phone = phoneNumber.value.trim();
      
      if (!validatePhone(phone)) {
        return;
      }
      
      // 禁用按钮
      getCodeBtn.disabled = true;
      getCodeBtn.textContent = '发送中...';
      

        const response = await fetch(`${API_BASE_URL}/api/login/getCode`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: `phoneNumber=${encodeURIComponent(phone)}`
        });
        
        const data = await response.json();
        console.log('sdata',data)
        if (data.success) {
          showToast('验证码发送成功，请注意查收');
          // 倒计时
          startCountdown();
        } else {
          showToast(data.message || '验证码发送失败', false);
          // 恢复按钮
          getCodeBtn.disabled = false;
          getCodeBtn.textContent = '获取验证码';
        }

    }
    
    // 倒计时功能
    function startCountdown() {
      let countdown = 60;
      getCodeBtn.textContent = `重新发送(${countdown}s)`;
      
      const timer = setInterval(() => {
        countdown--;
        getCodeBtn.textContent = `重新发送(${countdown}s)`;
        
        if (countdown <= 0) {
          clearInterval(timer);
          getCodeBtn.disabled = false;
          getCodeBtn.textContent = '获取验证码';
        }
      }, 1000);
    }
    
    // 登录功能
    async function login() {
      const phone = phoneNumber.value.trim();
      const codeValue = code.value.trim();
      
      // 前端验证
      if (!validatePhone(phone) || !validateCode(codeValue)) {
        return;
      }
      
      // 禁用按钮
      loginBtn.disabled = true;
      loginBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 登录中...';
      
      try {
        const response = await fetch(`${API_BASE_URL}/api/login/verify`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: `phoneNumber=${encodeURIComponent(phone)}&code=${encodeURIComponent(codeValue)}`
        });
        
        const data = await response.json();
        
        if (data.success) {
          // 保存token
          localStorage.setItem('token', data.data);
          showToast('登录成功，正在跳转...');
          
          // 模拟跳转
          setTimeout(() => {
            window.location.href = '/home.html'; // 替换为实际的首页URL
          }, 1500);
        } else {
          showToast(data.message || '登录失败', false);
          // 恢复按钮
          loginBtn.disabled = false;
          loginBtn.innerHTML = '<span>登录</span><i class="fa fa-arrow-right ml-2"></i>';
        }
      } catch (error) {
        console.error('登录失败:', error);
        showToast('网络错误，登录失败', false);
        // 恢复按钮
        loginBtn.disabled = false;
        loginBtn.innerHTML = '<span>登录</span><i class="fa fa-arrow-right ml-2"></i>';
      }
    }
    
    // 事件监听
    phoneNumber.addEventListener('blur', () => {
      validatePhone(phoneNumber.value.trim());
    });
    
    code.addEventListener('blur', () => {
      validateCode(code.value.trim());
    });
    
    getCodeBtn.addEventListener('click', sendVerificationCode);
    
    loginForm.addEventListener('submit', (e) => {
      e.preventDefault();
      login();
    });
    
    registerLink.addEventListener('click', (e) => {
      e.preventDefault();
      showToast('注册功能即将上线，敬请期待');
      // 实际项目中这里可以跳转到注册页面
      // window.location.href = '/register.html';
    });
    
    // 输入框实时格式化
    phoneNumber.addEventListener('input', (e) => {
      // 只保留数字
      e.target.value = e.target.value.replace(/[^\d]/g, '');
    });
    
    code.addEventListener('input', (e) => {
      // 只保留数字
      e.target.value = e.target.value.replace(/[^\d]/g, '');
    });
  </script>
</body>
</html>